//
//  SGSProfileROTableViewController.m
//  AgileNYC
//
//  Created by German on 01.08.14.
//  Copyright (c) 2014 Softlegion. All rights reserved.
//

#import "SGSProfileROTableViewController.h"
#import "SGSProfileROViewController.h"
#import "SGSModelsManager.h"
#import "SGSUtils.h"
#import "SGSAppConsts.h"
//#import "SGSUnderlinedButton.h"
#import <FacebookSDK/FacebookSDK.h>

@interface SGSProfileROTableViewController () <UITextViewDelegate>

@property (assign, nonatomic) BOOL isContactChanged;

@end

@implementation SGSProfileROTableViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.edNotes.delegate = self;

    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    
    if (modelsManager.currentRequester) {
        self.forUser = modelsManager.currentRequester;
        self.cellNotes.hidden = YES;
        self.cellNotesLine.hidden = YES;
    } else {
        self.forUser = modelsManager.currentContact;
        self.cellNotes.hidden = NO;
        self.cellNotesLine.hidden = NO;
    }
    
    self.tblContactView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.isContactChanged = NO;
    
    [self loadDataToControls];
    
    GSLog(GSLogEvent, @"----- SGSProfileROTableViewController Did Load");
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self saveContactData];
    
    GSLog(GSLogEvent, @"----- SGSProfileROTableViewController Will Disappear");
}

#pragma mark - Internal Procedures

-(void) loadDataToControls
{
    SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
    
    [self.spinnerPhoto startAnimating];
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    
    [modelsManager requestImageForContactByContact:self.forUser onComplete:^(BOOL result, UIImage *image) {
        self.imgProfilePhoto.image = image;
        [self.spinnerPhoto stopAnimating];
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
    }];
    
    self.labFullName.textAlignment = NSTextAlignmentLeft;
    self.labFullName.lineBreakMode = NSLineBreakByWordWrapping;
    self.labFullName.numberOfLines = 0;
    
    self.labTitle.textAlignment = NSTextAlignmentLeft;
    self.labTitle.lineBreakMode = NSLineBreakByWordWrapping;
    //self.labTitle.numberOfLines = 0;

    self.labCompany.textAlignment = NSTextAlignmentLeft;
    self.labCompany.lineBreakMode = NSLineBreakByWordWrapping;
    //self.labCompany.numberOfLines = 0;
    
    self.labMemo.textAlignment = NSTextAlignmentLeft;
    self.labMemo.lineBreakMode = NSLineBreakByWordWrapping;
    //self.labMemo.numberOfLines = 0;
    
    self.labFullName.text           = [self.forUser fullName];
    self.labTitle.text              = [self.forUser title];
    self.labCompany.text            = [self.forUser company];

    [self alignCaptions];
    
    self.edNotes.text            = self.forUser.notes;
    self.labMemo.text            = self.forUser.memo;
    self.labLocation.text        = [self.forUser location];
    self.labCode.text            = self.forUser.sessionID;
    
    NSDictionary *attrDict = @{NSFontAttributeName : [self.btnMail.titleLabel font],NSForegroundColorAttributeName : COLOR_MAIN_BLACK};
    NSMutableAttributedString *title;
    
    if ((self.forUser.eMail) && ([self.forUser.eMail length]>0)) {
        title =[[NSMutableAttributedString alloc] initWithString:self.forUser.eMail attributes: attrDict];
        
        [self.btnMail setAttributedTitle:title forState:UIControlStateNormal];
    } else {
      self.cellEmail.hidden = YES;
    }
    
    if ((self.forUser.webSite) && ([self.forUser.webSite length]>0)) {

        title =[[NSMutableAttributedString alloc] initWithString:self.forUser.webSite attributes: attrDict];
        
        [self.btnWebSite setAttributedTitle:title forState:UIControlStateNormal];
    } else {
      self.cellWebSite.hidden = YES;
    }
    
    if ((self.forUser.facebookId) && ([self.forUser.facebookId length]>0)) {
        
        if ((self.forUser.facebookName) && ([self.forUser.facebookName length]>0)) {
            title =[[NSMutableAttributedString alloc] initWithString:self.forUser.facebookName attributes: attrDict];
        } else if ([self.forUser.fullName length]>0) {
            title =[[NSMutableAttributedString alloc] initWithString:self.forUser.fullName attributes: attrDict];
        } else {
            title =[[NSMutableAttributedString alloc] initWithString:self.forUser.facebookId attributes: attrDict];
        }
        
        [self.btnFacebook setAttributedTitle:title forState:UIControlStateNormal];
    } else {
        self.cellFacebook.hidden = YES;
    }
    
    if ((self.forUser.linkedInId) && ([self.forUser.linkedInId length]>0)) {

        if ((self.forUser.linkedInName) && ([self.forUser.linkedInName length]>0)) {
            title =[[NSMutableAttributedString alloc] initWithString:self.forUser.linkedInName attributes: attrDict];
        } else if ([self.forUser.fullName length]>0) {
            title =[[NSMutableAttributedString alloc] initWithString:self.forUser.fullName attributes: attrDict];
        } else {
            title =[[NSMutableAttributedString alloc] initWithString:self.forUser.linkedInId attributes: attrDict];
        }

        [self.btnLinkedIn setAttributedTitle:title forState:UIControlStateNormal];
    } else {
      self.cellLinkedIn.hidden = YES;
    }

    if ((self.forUser.googlePlusId) && ([self.forUser.googlePlusId length]>0)) {

        if ((self.forUser.googlePlusName) && ([self.forUser.googlePlusName length]>0)) {
            title =[[NSMutableAttributedString alloc] initWithString:self.forUser.googlePlusName attributes: attrDict];
        } else if ([self.forUser.fullName length]>0) {
            title =[[NSMutableAttributedString alloc] initWithString:self.forUser.fullName attributes: attrDict];
        } else {
            title =[[NSMutableAttributedString alloc] initWithString:self.forUser.googlePlusId attributes: attrDict];
        }
        
        [self.btnGooglePlus setAttributedTitle:title forState:UIControlStateNormal];
    } else {
      self.cellGooglePlus.hidden = YES;
    }
    
    if ((self.forUser.phone) && ([self.forUser.phone length]>0)) {

        NSString * fmtPhoneNumber = getFormattedPhoneNumber(self.forUser.phone);
        
        if ((fmtPhoneNumber) && ([fmtPhoneNumber length]>0)) {
            title =[[NSMutableAttributedString alloc] initWithString:fmtPhoneNumber attributes: attrDict];
            
            [self.btnPhone setAttributedTitle:title forState:UIControlStateNormal];
        } else {
          self.cellPhone.hidden = YES;
        }
    } else {
      self.cellPhone.hidden = YES;
    }
    
    self.cellMemo.hidden        = ([self.labMemo.text length] == 0);
    self.cellMemoLine.hidden    = ([self.labMemo.text length] == 0);
    self.cellLocation.hidden    = ([self.labLocation.text length] == 0);
}

-(void) saveContactData {
    
    if (self.isContactChanged) {
        SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
        
        GSUser * currContact = modelsManager.currentContact;
        
        currContact.notes = self.edNotes.text;
        currContact.isChanged = [NSNumber numberWithBool:YES];
        currContact.modifiedDate = [NSDate date];
        
        [[SGSModelsManager sharedModelsManager] saveContactNotesAndSendToServer:currContact notes:self.edNotes.text];
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 14;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
    if (cell.hidden) {
        return 0;
    } else {
        return [super tableView:tableView heightForRowAtIndexPath:indexPath];
    }
}

#pragma mark - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView {
   self.isContactChanged = YES;
}

#pragma mark - System Functions

- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];}

#pragma mark - Actions

- (IBAction)onEmailButtonClick:(UIButton *)sender {
    NSString *email = [NSString stringWithFormat:@"mailto:%@",self.forUser.eMail];
    
    email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}

- (IBAction)onWebSiteButtonClick:(UIButton *)sender {
    NSString* urlString = self.forUser.webSite;
    
    NSRange prefixRange = [urlString rangeOfString:@"http"
                                      options:(NSAnchoredSearch | NSCaseInsensitiveSearch)];

    if (prefixRange.location == NSNotFound) {
        urlString = [NSString stringWithFormat:@"http://%@",urlString];
    }
    
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString: urlString];
    
    if (![[UIApplication sharedApplication] openURL:url]) {
        NSLog(@"%@%@",@"Failed to open url:",[url description]);
    }
}

- (IBAction)onGooglePlusButtonClick:(UIButton *)sender {
    NSString *url = [NSString stringWithFormat:@"https://plus.google.com/%@",self.forUser.googlePlusId];
    
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

- (IBAction)onLinkedInButtonClick:(UIButton *)sender {
    NSString *url = [NSString stringWithFormat:@"%@",self.forUser.linkedInId];
    
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

- (IBAction)onFacebookButtonClick:(UIButton *)sender {
    NSString *url = [NSString stringWithFormat:@"https://facebook.com/%@",self.forUser.facebookId];
    //NSString *url = [NSString stringWithFormat:@"fb://profile/%@",self.forUser.facebookId];
    //NSString *url = [NSString stringWithFormat:@"fb://profile/%@",@"German.Sidorenko"];
    //NSString *url = [NSString stringWithFormat:@"fb://facebook.com/%@",self.forUser.facebookId];
    //NSString *url = [NSString stringWithFormat:@"fb://facebook.com/id=%@",self.forUser.facebookId];
    
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]]){
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    }
    else {
        url = [NSString stringWithFormat:@"https://facebook.com/%@",self.forUser.facebookId];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    }
    
    //[FBSession.activeSession handleOpenURL:[NSURL URLWithString:url]];
    //[[SGSModelsManager sharedModelsManager] showProfileInFacebookForURL:url onComplete:nil];
}

- (IBAction)onPhoneButtonClick:(UIButton *)sender {
    NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
    NSString *phone = [[[NSString stringWithFormat:@"%@",self.forUser.phone] componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString: @""];

    phone = [NSString stringWithFormat:@"tel://%@",phone];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phone]];
}

#pragma mark - MFMessageComposeViewControllerDelegate

- (IBAction)onSendSMSButtonClick:(UIButton *)sender {
    
    NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
    NSString *phone = [[[NSString stringWithFormat:@"%@",self.forUser.phone] componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString: @""];
    
    phone = [NSString stringWithFormat:@"sms://%@",phone];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phone]];

}

#pragma mark - Align functions

-(void) alignCaptions {
    CGFloat sizeBetweenLabels = 6.0f;
    CGSize fullNameLabelSize;
    CGSize titleLabelSize;
    CGSize companyLabelSize;
    CGFloat centerY;
    CGFloat positionY;
    
    if ([[self.labFullName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        fullNameLabelSize = CGSizeMake(0, 0);
    } else {
        fullNameLabelSize = labelSize(self.labFullName, self.labFullName.frame.size.width, self.labFullName.frame.size.height);
    }

    if ([[self.labTitle.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        titleLabelSize = CGSizeMake(0, 0);
    } else {
        titleLabelSize = labelSize(self.labTitle, self.labTitle.frame.size.width, self.labTitle.frame.size.height);
    }

    if ([[self.labCompany.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        companyLabelSize = CGSizeMake(0, 0);
    } else {
        companyLabelSize = labelSize(self.labCompany, self.labCompany.frame.size.width, self.labCompany.frame.size.height);
    }
    
    CGFloat heightToBound = self.imgProfilePhoto.frame.size.height;
    
    // Calculate total height of all labels
    CGFloat totalLabelsHeight = fullNameLabelSize.height;
    
    if (titleLabelSize.height>0) totalLabelsHeight += sizeBetweenLabels;

    totalLabelsHeight += titleLabelSize.height;
    
    if (companyLabelSize.height>0) totalLabelsHeight += sizeBetweenLabels;
    
    totalLabelsHeight += companyLabelSize.height;

    // Try to align label and image

    if (totalLabelsHeight>heightToBound) {
        centerY = self.labFullName.frame.origin.y + (totalLabelsHeight/2);
        self.imgProfilePhoto.center = CGPointMake(self.imgProfilePhoto.center.x, centerY);
    } else {
        centerY = self.imgProfilePhoto.center.y;
        
        positionY = self.imgProfilePhoto.frame.origin.y + ((self.imgProfilePhoto.frame.size.height-totalLabelsHeight) / 2);
        
        self.labFullName.frame = CGRectMake(self.labFullName.frame.origin.x,
                                             positionY,
                                             fullNameLabelSize.width, fullNameLabelSize.height);
        
        positionY += fullNameLabelSize.height;

        if (titleLabelSize.height>0) positionY += sizeBetweenLabels;
        
        self.labTitle.frame = CGRectMake(self.labTitle.frame.origin.x,
                                            positionY,
                                            titleLabelSize.width, titleLabelSize.height);

        positionY += titleLabelSize.height;
        
        if (companyLabelSize.height>0) positionY += sizeBetweenLabels;
        
        self.labCompany.frame = CGRectMake(self.labCompany.frame.origin.x,
                                         positionY,
                                         companyLabelSize.width, companyLabelSize.height);

    }
    
    

}

@end
